package com.yy.micro.magic.data.service.code.impl;

import com.yy.micro.magic.data.domain.CodeItemVo;
import com.yy.micro.magic.data.entity.CodeMapItemEntity;
import com.yy.micro.magic.data.repository.CodeItemRepository;
import com.yy.micro.magic.data.service.code.MagicCodeItemService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Component
public class MagicCodeItemServiceImpl implements MagicCodeItemService {

    @Autowired
    private CodeItemRepository repository;
    @Override
    public CodeItemVo apply(final CodeItemVo vo) {
        CodeMapItemEntity item =repository.save(vo.to());
        return CodeItemVo.create().from(item);
    }

    @Override
    public CodeItemVo load(final Long id) {
        Optional<CodeMapItemEntity> item =repository.findById(id);
        if (item.isPresent()){
            return CodeItemVo.create().from(item.get());
        }
        return null;
    }

    @Override
    public List<CodeItemVo> findByCodeId(final Long codeId) {
        List<CodeMapItemEntity> entities =repository.findByCodeIdAndDisable(codeId,false);
        if (!CollectionUtils.isEmpty(entities)){
            return entities.stream().map(e->CodeItemVo.create().from(e)).collect(Collectors.toList());
        }
        return null;
    }
}
